define(["jquery", "easy-admin"], function ($, ea) {

    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: '/shop/admin/goods',
        add_url: '/shop/admin/goods/create',
        edit_url: '/shop/admin/goods/edit',
        delete_url: '/shop/admin/goods/destroy',
    };

    return {
        specs: [],
        index: function () {

            ea.table.render({
                init: init,
                cols: [[
                    {type: "checkbox"},
                    {field: 'id', width: 80, title: '序号'},
                    {field: 'goods_name', minWidth: 80, title: '名称', search: true},
                    {field: 'category.name', minWidth: 80, title: '分类', search: true},
                    {field: 'shop_price', minWidth: 80, title: '价格'},
                    {field: 'market_price', minWidth: 80, title: '市场价'},
                    {field: 'stock', minWidth: 80, title: '库存'},
                    {field: 'view', minWidth: 80, title: '浏览数'},
                    {field: 'created_at', minWidth: 120, title: '创建时间'},
                    {
                        width: 250,
                        title: '操作',
                        templet: ea.table.tool,
                        operat: [
                            'edit',
                            'delete'
                        ]
                    }
                ]],
            });

            ea.listen();
        },
        create: function () {

            this.spec();
            this.mobile();
            this.albums();

            ea.listen();
        },
        edit: function () {

            this.spec();
            this.mobile();
            this.albums();

            if (specArray.length > 0) {
                this.specAction();
            }

            ea.listen();
        },
        albums: function () {

            $('.delete-item').unbind("click").click(function () {
                $(this).parents(".layui-card").remove();
            });

            $('#add-albums-button').click(
                function () {

                    $('#albums-tpl').find('[data-upload]').attr('data-load', '').html();

                    var html = $('#albums-tpl').html();

                    var len = $('#albums-tab').find('.layui-card').length;
                    html = html.replaceAll("{num}", len);

                    $('#albums-button').before(html);

                    $('.delete-item').unbind("click").click(function () {
                        $(this).parents(".layui-card").remove();
                    });

                    ea.api.upload();
                }
            );
        },
        mobile: function () {

            $('.delete-item').unbind("click").click(function () {
                $(this).parents(".layui-card").remove();
            });

            $('#add-mobile-button').click(
                function () {

                    $('#mobile-tpl').find('[data-upload]').attr('data-load', '').html();

                    var html = $('#mobile-tpl').html();

                    var len = $('#mobile-tab').find('.layui-card').length;
                    html = html.replaceAll("{num}", len);

                    $('#mobile-button').before(html);

                    $('.delete-item').unbind("click").click(function () {
                        $(this).parents(".layui-card").remove();
                    });

                    ea.api.upload();
                }
            );
        },
        spec: function () {

            var that = this;

            $('#add-spec-button').click(
                function () {

                    var num = 0;

                    if ($('.spec-item').length > 0) {
                        var itemNums = [];
                        $('.spec-item').each(function (index, item) {
                            var tmp = parseInt($(item).attr('data-num'));
                            itemNums.push(!isNaN(tmp) ? tmp : 0);
                        });
                        num = Math.max.apply(null, itemNums) + 1;
                    }

                    var html = $('#spec-tpl').html();
                    html = html.replaceAll("{num}", num);

                    $('#spec-button').before(html);

                    that.specJs();
                }
            );

            this.specJs();

        }, specJs: function () {

            var that = this;

            $('#make-spec-button').unbind("click").click(function () {
                that.specAction();
            });

            $('.delete-spec-item').unbind("click").click(function () {
                $(this).parents(".layui-card").remove();
            });

            $('.add-spec-val-btn').unbind("click").click(function () {

                var html = $(this).parents(".layui-card").find('.specVal').find('.layui-input-inline').eq(0).html();
                var tmpEle = $('<div class="layui-input-inline">' + html + '</div>');
                var itemId = $(this).parents(".layui-card").find('.spec-item').attr('data-num');
                tmpEle.find('input').attr('value', '');
                tmpEle.find('input').attr('name', 'specVal[' + itemId + '][]');
                html = tmpEle.html();
                $(this).parents(".layui-card").find('.specVal').append('<div class="layui-input-inline">' + html + '</div>');
            });
        }, specAction: function () {

            this.specs = [];
            var items = [];
            var values = [];

            var tableEle = $('#spec-table');

            $('.spec-item').each(function (index, item) {

                var val = [];

                $('.specVal').eq(index).find('input').each(function (index, item) {
                    if ($(item).val()) {
                        val.push($(item).val());
                    }
                });

                if ($(item).val() && val.length > 0) {
                    items.push($(item).val());
                    values.push(val);
                }

            });

            var html = '';
            var thead = ['商品规格', '图片', '库存', '销售价', '市场价'];

            if (items.length > 0) {

                html += '<tr>';
                for (var i in thead) {
                    html += i == 0 ? '<th colspan="' + items.length + '">' + thead[i] + '</th>' : '<th rowspan="2">' + thead[i] + '</th>';
                }
                html += '</tr>';

                html += '<tr>';
                for (var i in items) {
                    html += '<th>' + items[i] + '</th>'
                }
                html += '</tr>';


                html += this.specTableHtml(values);


                tableEle.html(html);
                tableEle.show();

                ea.api.upload();
            }
        }, specArray: function (index, subContext, values) {

            let stringList = values[index];

            for (let i in stringList) {

                let e = stringList[i];

                if (index !== 0) {
                    e = subContext + ";" + e;
                }

                if (values.length === 1) {
                    this.specs.push(e);
                } else {
                    if (index === (values.length - 1) && index !== 0) {
                        this.specs.push(e);
                    } else {
                        this.specArray(index + 1, e, values);
                    }
                }

            }
        }, specTableHtml: function (values) {

            var html = '';

            this.specArray(0, '', values);

            if (this.specs.length > 0) {

                for (var ii in this.specs) {

                    var item = Object.assign({
                        id: '',
                        img: '',
                        stock: '',
                        shop_price: '',
                        market_price: ''
                    }, specArray[this.specs[ii]] ? specArray[this.specs[ii]] : {});

                    var array = this.specs[ii].split(";");

                    html += '<tr>';

                    for (var iii in array) {

                        html += '<td>' + array[iii] + '</td>';
                    }

                    html += '<td><input type="hidden" name="spec_ids[' + ii + ']" value="' + item['id'] + '"><div class="layui-input-block layuimini-upload">\n' +
                        '                            <input name="spec_img[' + ii + ']" class="layui-input layui-col-xs6" placeholder="请上传缩略图" value="' + item['img'] + '">\n' +
                        '                            <div class="layuimini-upload-btn">\n' +
                        '                            <span><a class="layui-btn" data-upload="spec_img[' + ii + ']" data-upload-number="one"\n' +
                        '                                     data-upload-exts="ico|png|jpg|jpeg"><i class="fa fa-upload"></i> 上传</a></span>\n' +
                        '                            </div>\n' +
                        '                        </div></td>';

                    html += '<td><input class="layui-input layui-table-edit" placeholder="库存" name="spec_stock[' + ii + ']" value="' + item['stock'] + '"></td>';

                    html += '<td><input class="layui-input layui-table-edit" placeholder="销售价" name="spec_shop_price[' + ii + ']" value="' + item['shop_price'] + '"></td>';

                    html += '<td><input class="layui-input layui-table-edit" placeholder="市场价" name="spec_market_price[' + ii + ']" value="' + item['market_price'] + '"></td>';

                    html += '</tr>';
                }
            }

            return html;
        }
    };
});
